﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';

    var checkWorkload = (rule, value, callback) => {
        if (!value) {
            return callback(new Error("请输入工作量系数"));
        }
        if (value <= 0) {
            return callback(new Error("必须大于0"))
        }
        callback()
    };
    // 实例
    var vm = new Vue({
        el: '#app',
        components: {
            'tree-selector': TreeSelectorComponent // 局部注册组件
        },
        data: {

            // 角色与权限
            examItemPermission: true, // 能进到本页面，就是true
            examItemAddPermission: false,
            examItemEditPermission: false,
            examItemDeletePermission: false,
            examItemSyncDataPermission:false,
            multiDepartmentPermission: false,

            // 主页面
            filterName: '',
            dialogVisible: false, // 创建用户对话框，是否显示
            dialogTitle: '新建', 
            actionType: '新建项目',
            showApplicableSex:false,
            tableData: [],  
            formLabelWidth: '80px',
            department: null,   // 当前科室
            deviceType:null,    // 当前设备类型
            treeData: [],
            currentPage: 1,    // 页码
            totalCount: 0,
            pageSize: 10,
            selectedExamItems: [],
            showWorkLoad:false,

            // 下拉选项你
            deviceTypeOptions: [],
            applicableSexOptions: [],
            deviceOptions:[],
               

            examItem: {
                id:null,
                name: null,
                code: null,
                outerCode: null,
                deviceTypeId: null,
                applicableSex: null,
                workload:1,
                parent: null,
                parentName: null,
                parentId:null,
                order: 0,
                devices: [],
                requireInterval: false,
                startTime: null,
                endTime:null,
                isDirectory: false,
                isActive: true
            },

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 验证规则
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ],
                outerCode: [
                    { required: true, message: '请输入外部编号', trigger: 'blur' }
                ],
                deviceTypeId: [
                    {required:true,message:'请选择设备类型'}
                ],
                workload: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { validator: checkWorkload, trigger: 'blur' }
                ]
            }
        },
        computed: {
            tableShow: function () {
                var vm = this;
                if ((vm.treeData[0] && vm.treeData[0].children.length > 0) || vm.department) {
                    return true;
                }
                return false;
            }
        },
        watch: {
            department: function () {
                var vm = this;
                vm.loadDepartmentDeviceTypeOptions(); // 重新加载科室设备类型选项
            }
        },
        methods: {
            // 自定义表单验证器
            isRequired(rule, value, callback) {
                const vm = this;
                if (vm.examItem.requireInterval) {
                    if (!vm.examItem.startTime) {
                        return callback(new Error('请选择开始时间'));
                    }
                    if (!vm.examItem.endTime) {
                        return callback(new Error('请选择结束时间'));
                    }
                    callback();
                }
            },

            // 同步科室设备类型下检查项目
            syncData() {
                var vm = this;
                abp.message.confirm(`科室-${vm.department.name}，设备类型-${vm.deviceType.name}，同步检查项目`)
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/exam-item/async?depId=${vm.department.id}&deviceTypeId=${vm.deviceType.id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    vm.loadExamItemList();
                                    abp.notify.success(res.msg);
                                }
                            })
                        }
                    })
            },

            // 加载科室设备类型选项
            loadDepartmentDeviceTypeOptions() {
                var vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/exam-item/get-dep-device-type-options?depId=${vm.department.id}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.deviceTypeOptions = res.data;
                    }
                });
            },

            // 加载适用性别选项
            loadApplicableSexOptions() {
                var vm = this;
                abp.ajax({
                    type: 'get',
                    url: '/api/exam-item/get-applicable-sex-options'
                }).then(res => {
                    if (res.code === 0) {
                        vm.applicableSexOptions = res.data;
                    }
                });
            },

            // 当前页改变
            currentPageChange(val) {
                var vm = this;
                vm.currentPage = val;
                vm.loadExamItemList();
            },

            // 每页数量改变
            pageSizeChange(val) {
                var vm = this;
                vm.pageSize = val;
                vm.currentPage = 1;
                vm.loadExamItemList();
            },

            // 选中检查项目改变
            selectionExamItemChange(val) {
                var vm = this;
                vm.selectedExamItems = val;
            },

            // 加载表格数据(只在初始化时执行一次)
            loadTableData() {
                var vm = this;
                return new Promise(resolve => {
                    if (vm.multiDepartmentPermission && vm.treeData[0].children.length > 0) { // admin 角色下，有科室
                        //vm.department = vm.treeData[0].children[0]; // 默认加载tree中的第一个科室的用户情况
                        vm.loadExamItemList();
                    }
                    else if (vm.multiDepartmentPermission && vm.treeData[0].children.length === 0) { // admin角色下，系统中还没创建任何科室
                        // 提示系统还没有任何科室
                    }
                    else if (!vm.multiDepartmentPermission) { // 必然时是科室用户，而且必然是已经登录了某个科室，而且已经加载了科室
                        // 根据登录科室加载
                        vm.loadExamItemList();
                    }
                    resolve();
                })
               
            },

            // 加载科室设备类型下检查项目列表
            loadExamItemList() {
                var vm = this;
                abp.ajax({
                    type: 'GET',
                    url: `/api/exam-item/get-exam-item-tree-list?depId=${vm.department.id}&deviceTypeId=${vm.deviceType.id}&filterName=${vm.filterName}&page=${vm.currentPage}&pageSize=${vm.pageSize}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.tableData = res.data.list;
                        vm.totalCount = res.data.total;
                    }
                });
            },


            // 显示新建检查项目对话框
            showCreate() {
                var vm = this;
                vm.dialogTitle = '新建项目';
                vm.actionType = '新建项目';
                vm.examItem.isDirectory = false;
                vm.examItem.applicableSex = 0;
                vm.examItem.workload = 1;
                vm.examItem.order = 0;
                vm.examItem.isActive = true;
                vm.examItem.requireInterval = false;
                vm.showApplicableSex = true;
                vm.examItem.deviceTypeId = vm.deviceType.id;
                vm.loadDeviceOptionsByDeviceType(vm.deviceType.id);
                var dirList = vm.selectedExamItems.filter(item => item.isDirectory);
                if (dirList.length > 0) {
                    vm.examItem.parentId = dirList[0].id;
                    vm.examItem.parentName = dirList[0].name;
                }
                vm.dialogVisible = true;
            },

            // 打开新建目录对话框
            showCreateDir() {
                var vm = this;
                vm.dialogTitle = '新建目录';
                vm.actionType = '新建目录';
                vm.examItem.applicableSex = 0;
                vm.showApplicableSex = false;
                vm.examItem.deviceTypeId = vm.deviceType.id;
                vm.examItem.isActive = true;
                vm.examItem.isDirectory = true;
                vm.examItem.order = 0;
                vm.examItem.requireInterval = false;
                var dirList = vm.selectedExamItems.filter(item => item.isDirectory);
                if (dirList.length > 0) {
                    vm.examItem.parentId = dirList[0].id;
                    vm.examItem.parentName = dirList[0].name;
                }
                vm.dialogVisible = true;
            },

            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/exam-item/submit-create?depId=${vm.department.id}&deviceTypeId=${vm.deviceType.id}`,
                            data: JSON.stringify(vm.examItem)
                        }).then(res => {
                            if (res.code == 0) {
                                vm.resetForm();
                                vm.loadExamItemList();
                                abp.notify.success(res.msg);
                            }
                            else {
                                abp.message.error(res.msg);
                            }
                        });
                    }
                });

            },

            // 监听设备类型改变
            deviceTypeChangeHandler(val) {
                const vm = this;
                vm.examItem.devices = [];
                vm.loadDeviceOptionsByDeviceType(val);
            },

            // 根据检查项目获取设备选项
            loadDeviceOptions(id) {
                const vm = this;
                abp.ajax({
                    type:'get',
                    url: `/api/exam-item/get-device-options?examItemId=${id}`,
                }).then(res => {
                    if (res.code == 0) {
                        vm.deviceOptions = res.data;
                    }
                })
            },

            // 根据设备类型获取设备选项
            loadDeviceOptionsByDeviceType(deviceTypeId) {
                const vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/exam-item/get-device-options-by-devicetype?deviceTypeId=${deviceTypeId}`
                }).then(res => {
                    if (res.code == 0) {
                        vm.deviceOptions = res.data;
                    }
                })
            },




            // 打开编辑窗口
            showEdit(id) {
                var vm = this;
                vm.loadDeviceOptions(id);
                vm.loadDetail(id).then((data) => {
                    vm.dialogVisible = true;
                    if (data.isDirectory) {
                        vm.dialogTitle = '编辑目录';
                        vm.actionType =  '编辑目录';
                    }
                    else {
                        vm.dialogTitle = '编辑检查项目';
                        vm.actionType = '编辑检查项目';
                    }
                });
            },

            // 编辑提交
            submitEdit() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: '/api/exam-item/submit-edit',
                            data: JSON.stringify(vm.examItem)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadExamItemList();
                            }
                            else {
                                abp.message.error(res.msg);
                            }
                        })
                    }
                });
            },

            save() {
                var vm = this;
                var url = `/api/exam-item/submit-create?depId=${vm.department.id}&deviceTypeId=${vm.deviceType.id}`;
                if (vm.actionType.includes('编辑')) {
                    url = `/api/exam-item/submit-edit`;
                }
                vm.$refs['dialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: url,
                            data: JSON.stringify(vm.examItem)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadExamItemList();
                                vm.resetForm();
                            }
                        });
                    }
                })
            },

            // 删除多个
            deleteMany() {
                var vm = this;
                if (vm.selectedExamItems.length === 0) {
                    abp.notify.error('请选中要删除的检查项目或目录！');
                }
                else {
                    abp.message.confirm('删除选中检查项目和目录(包含其所有子级)')
                        .then(confirmed => {
                            if (confirmed) {
                                abp.ajax({
                                    type: 'post',
                                    url: `/api/exam-item/delete-many`,
                                    data: JSON.stringify(vm.selectedExamItems.map(item => item.id))
                                }).then((res) => {
                                    if (res.code === 0) {
                                        abp.notify.success(res.msg);
                                        vm.loadExamItemList();
                                    }
                                });
                            }
                        });
                }
            },

            // 删除单个
            deleteExamItem(id) {
                var vm = this;
                abp.message.confirm('删除检查项目/目录(包含其所有子级)')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/exam-item/delete?id=${id}`
                            }).then((res) => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadExamItemList();
                                }
                            })
                        }
                    });
            },

            // 加载检查项目详情
            loadDetail(id) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/exam-item/get?id=${id}`
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.examItem = res.data;
                            resolve(res.data);
                        }
                    })
                });
            },

            // 加载科室（如果是科室用户时）
            loadDepartment() {
                return new Promise(resolve => {
                    if (!vm.multiDepartmentPermission) {
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }
                    else {
                        resolve();
                    }
                });
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                var vm = this;
                return new Promise(resolve => {
                    var url;
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        url = `/api/exam-item/get-tree-data?depId=${null}`
                    }
                    else {
                        url= `/api/exam-item/get-tree-data?depId=${vm.department.id}`
                    }
                    abp.ajax({
                        type: "GET",
                        url: url
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.treeData = res.data;
                            if (vm.treeData[0].children.length > 0) { // 有科室存在
                                res.data[0].children.forEach((department, index) => {
                                    if (!vm.deviceType && department && department.children && department.children.length > 0) {
                                        vm.deviceType = vm.treeData[0].children[index].children[0];
                                        vm.department = department;
                                    }
                                })
                            }
                            else {
                                vm.tableShow = false;
                            }
                            resolve();
                        }
                    });
                });
            },

            // 加载当前权限
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('BaseSettingGroup.ExamItems')) { // 检查项目管理权限
                        vm.examItemPermission = true;
                        if (abp.auth.isGranted('BaseSettingGroup.ExamItems.Add')) {// 新建检查项目权限
                            vm.examItemAddPermission = true;
                        }

                        if (abp.auth.isGranted('BaseSettingGroup.ExamItems.Edit')) { // 编辑检查项目权限
                            vm.examItemEditPermission = true;
                        }

                        if (abp.auth.isGranted('BaseSettingGroup.ExamItems.Delete')) { // 删除检查项目权限
                            vm.examItemDeletePermission = true;
                        }

                        if (abp.auth.isGranted('BaseSettingGroup.ExamItems.Sync')) { // 同步数据权限
                            vm.examItemSyncDataPermission = true;
                        }
                    }
                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) { // 多科室检查项目管理权限
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击树节点
            nodeClicked(node,obj,aa) {
                if (node.icon != 'fa fa-hospital' && node.icon !='fa fa-building') {
                    var vm = this;
                    vm.filterName = '';
                    vm.deviceType = node;
                    vm.department = obj.parent.data;
                    vm.loadExamItemList();
                }
            },

            parentSetectedChange(data) {
                var vm = this;
                vm.examItem.parentId = data.id;
                vm.examItem.parentName = data.name;
            },

            // 创建科室用用户，表单重置
            resetForm() {
                var vm = this;
                vm.$refs['dialogForm'].resetFields();
                vm.dialogVisible = false;
                Object.keys(vm.examItem).forEach(key => {
                    vm.examItem[key] = null;
                });
            },

            // 初始化
            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadDepartment().then(() => {
                            vm.loadTreeData().then(() => {
                                vm.loadTableData().then(() => {
                                    vm.loadDepartmentDeviceTypeOptions();
                                });
                            });
                        })
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
            vm.loadApplicableSexOptions();
            vm.rules= {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ],
                outerCode: [
                    { required: true, message: '请输入外部编号', trigger: 'blur' }
                ],
                deviceTypeId: [
                    {required:true,message:'请选择设备类型'}
                ],
                workload: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { validator: checkWorkload, trigger: 'blur' }
                ],
                timeInterval: [
                    { validator: vm.isRequired,trigger:['blur'] }
                ]
            }
        },
        mounted() {
        }
    });
});